package com.cxj.link;

import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.cxj.link.task.LevelManager;
import com.cxj.link.task.TaskGameServiceImpl;
import com.cxj.link.util.ToastUtil;
import com.cxj.link.view.GameLogic;
import com.cxj.link.view.GameView;
import com.cxj.link.view.Cut;
import com.cxj.link.vo.GameConfig;
import com.cxj.link.vo.LinkVo;

public class TaskActivity extends Activity {
    private GameConfig config;
    private GameLogic gameService;
    private int gameTime;
    private GameView gameView;
    // 判断是否已经无剩余时间
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message paramMessage) {
            switch (paramMessage.what) {
            case 291:
                TaskActivity.this.levelBtn.setText("第" + (1 + Setting.level2) + "关");
                TaskActivity.this.timeTextView.setText("剩余时间: " + TaskActivity.this.gameTime);
                TaskActivity localTaskActivity = TaskActivity.this;
                localTaskActivity.gameTime -= 1;
                if (TaskActivity.this.gameTime >= 0)
                    break;
                TaskActivity.this.stopTimer();
                TaskActivity.this.isPlaying = false;
                TaskActivity.this.lostDialog.show();
            }
        }
    };
    private boolean isPlaying;
    private Button levelBtn;
    private AlertDialog.Builder levelDialog;// 选择关卡
    private AlertDialog.Builder lostDialog;// 失败提示
    private AlertDialog.Builder overDialog;// 过关提示
    private AlertDialog.Builder successDialog;// 通关提示
    private Button promptBtn;
    private Button refreshBtn;
    private Cut selected = null;// 已经选择的块
    private TextView timeTextView;
    private Timer timer = new Timer();

    private AlertDialog.Builder createDialog(String title, String message) {
        return new AlertDialog.Builder(this).setTitle(title).setMessage(message);
    }

    private void gameViewTouchDown(MotionEvent paramMotionEvent) {
        Cut[][] arrayOfPiece = this.gameService.getPieces();
        float f2 = paramMotionEvent.getX();
        float f1 = paramMotionEvent.getY();
        Cut localPiece = this.gameService.findPiece(f2, f1);
        if (localPiece != null) {
            SoundsManager.playSound(this, 1);
            this.gameView.setSelectedPiece(localPiece);
            if (this.selected != null) {
                if (this.selected != null) {
                    LinkVo localLinkInfo = this.gameService.link(this.selected, localPiece);
                    if (localLinkInfo != null) {
                        SoundsManager.playSound(this, 2);
                        handleSuccessLink(localLinkInfo, this.selected, localPiece, arrayOfPiece);
                    } else {
                        this.selected = localPiece;
                        this.gameView.setPromptPiece(null);
                        this.gameView.postInvalidate();
                    }
                }
            } else {
                this.selected = localPiece;
                this.gameView.postInvalidate();
            }
        }
    }

    private void gameViewTouchUp(MotionEvent paramMotionEvent) {
        this.gameView.postInvalidate();
    }

    private void handleSuccessLink(LinkVo paramLinkInfo, Cut paramPiece1, Cut paramPiece2,
            Cut[][] paramArrayOfPiece) {
        this.gameView.setLinkInfo(paramLinkInfo);
        this.gameView.setSelectedPiece(null);
        this.gameView.postInvalidate();
        paramArrayOfPiece[paramPiece1.getIndexX()][paramPiece1.getIndexY()] = null;
        paramArrayOfPiece[paramPiece2.getIndexX()][paramPiece2.getIndexY()] = null;
        this.selected = null;
        if (!this.gameService.hasPieces()) {
            if (Setting.level2 < 9)
                this.successDialog.show();
            else
                this.overDialog.show();
            stopTimer();
            this.isPlaying = false;
        }
    }

    // 初始化界面
    private void init() {
        //全屏显示
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        LevelManager.init(metrics.widthPixels, metrics.heightPixels, this);

        this.config = LevelManager.getLevel(Setting.level2);
        this.gameView = ((GameView) findViewById(2131099663));
        this.timeTextView = ((TextView) findViewById(2131099664));
        this.refreshBtn = ((Button) findViewById(2131099665));
        this.promptBtn = ((Button) findViewById(2131099666));
        this.levelBtn = ((Button) findViewById(2131099667));
        this.refreshBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View paramView) {
                SoundsManager.playSound(TaskActivity.this, 5);
                TaskActivity.this.refresh();
            }
        });
        this.promptBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View paramView) {
                TaskActivity.this.prompt();
            }
        });
        this.levelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View paramView) {
                TaskActivity.this.level();
            }
        });
        this.gameService = new TaskGameServiceImpl(this.config);
        this.gameView.setGameService(this.gameService);
        this.gameView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
                if (paramMotionEvent.getAction() == 0)
                    TaskActivity.this.gameViewTouchDown(paramMotionEvent);
                if (paramMotionEvent.getAction() == 1)
                    TaskActivity.this.gameViewTouchUp(paramMotionEvent);
                return true;
            }
        });
        this.lostDialog = createDialog("提示", "时间到了,你没消完哦,重新试试吧!!! ").setPositiveButton("重新开始",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        TaskActivity.this.startGame(TaskActivity.this.config.getGameTime());
                    }
                });
        this.successDialog = createDialog("提示", "恭喜您,过关啦!!!").setPositiveButton("进入下一关",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        Setting.level2 = 1 + Setting.level2;
                        TaskActivity.this.config = LevelManager.getLevel(Setting.level2);
                        TaskActivity.this.gameService.setConfig(TaskActivity.this.config);
                        TaskActivity.this.startGame(TaskActivity.this.config.getGameTime());
                    }
                });
        this.overDialog = createDialog("提示", "恭喜您,你通关啦,真厉害呀!!!").setPositiveButton("返回主菜单",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        Setting.level2 = 0;
                        TaskActivity.this.finish();
                    }
                });
    }

    private void level() {
        this.levelDialog = createDialog("提示", "当前第" + (1 + Setting.level2) + "关,一共有" + 10 + "关,加油呀!!")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    }
                });
        this.levelDialog.show();
    }

    private void prompt() {
        this.gameTime -= 5;
        ToastUtil.makeText(this, "使用提示功能,扣除5秒时间");
        Cut[] arrayOfPiece = this.gameService.getTwoPieces();
        if (arrayOfPiece != null)
            this.gameView.setPromptPiece(arrayOfPiece);
        else
            ToastUtil.makeText(this, "没有找到可消除的,请刷新");
        this.gameView.postInvalidate();
    }

    private void refresh() {
        this.gameService.refreshPieces();
        this.gameView.postInvalidate();
    }

    private void startGame(int paramInt) {
        if (this.timer != null)
            stopTimer();
        this.gameTime = paramInt;
        if (paramInt == this.config.getGameTime())
            this.gameView.startGame();
        this.isPlaying = true;
        this.timer = new Timer();
        this.timer.schedule(new TimerTask() {
            @Override
            public void run() {
                TaskActivity.this.handler.sendEmptyMessage(291);
            }
        }, 0L, 1000L);
        this.selected = null;
    }

    private void stopTimer() {
        if (this.timer != null) {
            this.timer.cancel();
            this.timer = null;
        }
    }

    @Override
    public void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        requestWindowFeature(1);
        setContentView(R.layout.task);
        init();
        startGame(this.config.getGameTime());
    }

    @Override
    protected void onPause() {
        stopTimer();
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (this.isPlaying)
            startGame(this.gameTime);
        super.onResume();
    }
}
